package com.example.gamestore.service.Impl;

import com.example.gamestore.mapper.GameMapper;
import com.example.gamestore.mapper.ShoppingCartMapper;
import com.example.gamestore.pojo.Game;
import com.example.gamestore.service.GameService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class GameServiceImpl implements GameService {
    @Resource
    private GameMapper gameMapper;


    @Resource
    private ShoppingCartMapper shoppingCartMapper; // 假设有购物车的Mapper

    // ... 其他方法 ...

    @Override
    @Transactional
    public void delete(Long id) {
        // 先删除购物车中关联的记录
        shoppingCartMapper.deleteByGameId(id);
        // 再删除游戏
        gameMapper.delete(id);
    }

    @Override
    @Transactional
    public Game add(Game game) {
        try {
            int rows = gameMapper.add(game);
            if (rows > 0) {
                return game;
            }
        } catch (Exception e) {
            // 记录日志
            e.printStackTrace();
        }
        return null;
    }

    /*@Override
    public void delete(Long id) {
        gameMapper.delete(id);
    }*/

    @Override
    public int updateGame(Game game) {
        try{
            return gameMapper.updateGame(game);
        } catch(Exception e){
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public List<Game> query() {
        System.out.println("进入到ganmeService");
        return gameMapper.query();
    }

    @Override
    public List<Game> searchGames(String key) {
        if (key == null || key.trim().isEmpty()) {
            return new ArrayList<>(); // 无关键词时返回空列表
        }
        return gameMapper.selectGamesByName("%" + key.trim() + "%"); // 传递带通配符的参数
    }

    @Override
    public Game getGameById(Long id) {
        return gameMapper.selectById(id);
    }

    @Override
    public List<Game> getRelatedGames(Long id, int limit) {
        // 这里简单实现，实际应用中可能需要更复杂的逻辑
        // 例如根据游戏类别、标签等查找相关游戏
        return gameMapper.selectRelatedGames(id, limit);
    }
}